import tushare as ts
import pandas as pd
import backtrader as bt
import datetime
class  GetTushareDat ():



    def getData(self,pro,stk_code,data,frequency,fromdate,todate):
        code =stk_code.split('.', 1)
        stk_code = code[1]+'.'+code[0]
        data=data.replace('-','')

        if frequency=='w':
          df = pro.weekly(ts_code=stk_code, start_date=data, end_date='%s%s%s' % (
                datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day),
                        fields='ts_code,trade_date,open,high,low,close,vol,amount').iloc[::-1]
        elif frequency=='m':
          df = pro.monthly(ts_code=stk_code, start_date=data, end_date='%s%s%s' % (
                datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day),
                            fields='ts_code,trade_date,open,high,low,close,vol,amount').iloc[::-1]
        else:
          df = pro.daily(ts_code=stk_code, start_date=data, end_date='%s%s%s' % (
                datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day),
                             fields='ts_code,trade_date,open,high,low,close,vol,amount').iloc[::-1]
        df.trade_date = pd.to_datetime(df.trade_date)  # 由于trade_date是字符串，BackTrader无法识别，需要转一下

        c =int(code[1])

        df.insert(loc=0, column='code', value=c)

        data = bt.feeds.PandasData(
            dataname=df,
            fromdate=fromdate,
            todate=todate,
            datetime='trade_date',
            open='open',
            high='high',
            low='low',
            close='close',
            volume='code',

            openinterest=-1
        )
        return data